import os
import logging
from dotenv import load_dotenv
import paho.mqtt.client as mqtt
from timelapse_cv import main as timelapse_main

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('mqtt_controller.log'),
        logging.StreamHandler()
    ]
)

# 加载环境变量
load_dotenv()

# MQTT配置
MQTT_BROKER = os.getenv('MQTT_BROKER', 'broker.emqx.io')
MQTT_PORT = int(os.getenv('MQTT_PORT', 1883))
MQTT_CLIENT_ID = os.getenv('MQTT_CLIENT_ID', 'pi_timelapse_controller')

TOPIC_CAMERA_STATUS = os.getenv('TOPIC_CAMERA_STATUS', "pi/camera/status")
TOPIC_SNAPSHOT = os.getenv('TOPIC_SNAPSHOT', "pi/camera/snapshot")

def on_connect(client, userdata, flags, rc):
    """MQTT连接回调
    client: 客户端实例
    userdata: 用户数据
    flags: 标志
    rc: 连接结果
    """
    if rc == 0:
        logging.info("Connected to MQTT broker")
        client.subscribe(TOPIC_SNAPSHOT)
        logging.info(f"Subscribed to topic: {TOPIC_SNAPSHOT}")
    else:
        logging.error(f"Failed to connect to MQTT broker with code: {rc}")

def on_message(client, userdata, msg):
    """MQTT消息接收回调
    client: 客户端实例
    userdata: 用户数据
    msg: 消息
    """
    try:
        command = msg.payload.decode()
        logging.info(f"Received command: {command}")
        
        if msg.topic == TOPIC_SNAPSHOT:
            # 启动timelapse_cv.py
            oss_image_url = timelapse_main()
            client.publish(TOPIC_CAMERA_STATUS, payload=oss_image_url, qos=1)
            logging.info(f"发布消息到{TOPIC_CAMERA_STATUS}，内容为{oss_image_url}")
            logging.info("完成执行拍照指令！")
        else:
            logging.warning(f"Unknown command: {command}")
            
    except Exception as e:
        logging.error(f"Error processing message: {str(e)}")

def main():
    """主函数"""
    client = mqtt.Client(client_id=MQTT_CLIENT_ID)
    client.on_connect = on_connect
    client.on_message = on_message

    try:
        client.connect(MQTT_BROKER, MQTT_PORT, 60)
        logging.info(f"Connecting to {MQTT_BROKER}:{MQTT_PORT}")
        
        # 启动MQTT循环
        client.loop_forever()
        
    except Exception as e:
        logging.error(f"Failed to connect: {str(e)}")
        
if __name__ == "__main__":
    main() 